import { setToken, getToken, removeToken } from '@/utils/auth'
import { login , getUserInfo} from '@/api/user'

const actions = {
  //  登录
  async login({ commit }, loginForm) {
    let { token } = await login(loginForm)
    commit('SET_TOKEN', token)
  },
  //  获取用户信息
  async getUserInfo({commit}){
    let data = await getUserInfo()
    commit('SET_USER_INFO',data)
  },
  //  退出登录
  logout({commit}){
    commit('LOG_OUT')
  }
}

const mutations = {
  SET_TOKEN(state, token) {
    // 保存到vuex
    state.token = token
    // 持久化到cookies
    setToken(token)
  },
  SET_USER_INFO(state,data){
    state.userInfo = data
  },
  LOG_OUT(state){
    //  清除用户信息
    state.userInfo = {}
    //  清除cookie中的token
    removeToken()
    //  重置state中的token
    state.token = null
  }
}

const state = {
  token: null,
  userInfo:{}
}

export default {
  // 开启命名空间
  namespaced: true,
  state,
  mutations,
  actions,
}
